import 'package:flutter/material.dart';
import '../models/sale_record.dart';
import '../models/sale_item.dart';

class SalesHistorySection extends StatefulWidget {
  const SalesHistorySection({Key? key}) : super(key: key);

  @override
  State<SalesHistorySection> createState() => _SalesHistorySectionState();
}

class _SalesHistorySectionState extends State<SalesHistorySection> {
  final TextEditingController _searchController = TextEditingController();
  String _selectedDateRange = 'today';
  String _selectedStatus = 'all';
  List<SaleRecord> _filteredSales = [];

  // ۋاقىتلىق سودا خاتىرىلىرى (كېيىن مەلۇمات ئامبىرىدىن ئېلىنىدۇ)
  final List<SaleRecord> _salesHistory = [
    SaleRecord(
      id: 'S001',
      customerName: 'ئابدۇللا',
      date: DateTime.now().subtract(const Duration(hours: 2)),
      items: [
        SaleItem(
          productName: 'ئالما',
          quantity: 3,
          price: 5.99,
          unit: 'كىلو',
        ),
        SaleItem(
          productName: 'ئۈزۈم',
          quantity: 2,
          price: 8.99,
          unit: 'كىلو',
        ),
      ],
      totalAmount: 35.95,
      paymentMethod: 'cash',
      status: 'completed',
    ),
    SaleRecord(
      id: 'S002',
      customerName: 'مەمەت',
      date: DateTime.now().subtract(const Duration(days: 1)),
      items: [
        SaleItem(
          productName: 'پىياز',
          quantity: 5,
          price: 3.99,
          unit: 'كىلو',
        ),
      ],
      totalAmount: 19.95,
      paymentMethod: 'card',
      status: 'completed',
    ),
  ];

  @override
  void initState() {
    super.initState();
    _filteredSales = _salesHistory;
    _searchController.addListener(_filterSales);
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  void _filterSales() {
    final query = _searchController.text.toLowerCase();
    setState(() {
      _filteredSales = _salesHistory.where((sale) {
        final matchesQuery = sale.customerName.toLowerCase().contains(query) ||
                           sale.id.toLowerCase().contains(query);
        final matchesStatus = _selectedStatus == 'all' || sale.status == _selectedStatus;
        final matchesDate = _isDateInRange(sale.date);
        return matchesQuery && matchesStatus && matchesDate;
      }).toList();
    });
  }

  bool _isDateInRange(DateTime date) {
    final now = DateTime.now();
    switch (_selectedDateRange) {
      case 'today':
        return date.year == now.year && 
               date.month == now.month && 
               date.day == now.day;
      case 'week':
        final weekAgo = now.subtract(const Duration(days: 7));
        return date.isAfter(weekAgo);
      case 'month':
        return date.year == now.year && date.month == now.month;
      case 'year':
        return date.year == now.year;
      default:
        return true;
    }
  }

  void _showSaleDetails(SaleRecord sale) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('سودا تەپسىلاتى - ${sale.id}'),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildDetailRow('خېرىدار:', sale.customerName),
              _buildDetailRow('ۋاقىت:', _formatDate(sale.date)),
              _buildDetailRow('تۆلەش ئۇسۇلى:', _getPaymentMethodText(sale.paymentMethod)),
              _buildDetailRow('ھالىتى:', _getStatusText(sale.status)),
              const Divider(),
              const Text(
                'سېتىۋالغان مەھسۇلاتلار:',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 8),
              ...sale.items.map((item) => Padding(
                padding: const EdgeInsets.only(left: 16),
                child: Text(
                  '${item.productName} - ${item.quantity} ${item.unit} × ¥${item.price.toStringAsFixed(2)} = ¥${(item.quantity * item.price).toStringAsFixed(2)}',
                ),
              )),
              const Divider(),
              _buildDetailRow(
                'جەمئىي سومما:',
                '¥${sale.totalAmount.toStringAsFixed(2)}',
                isTotal: true,
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('تامام'),
          ),
        ],
      ),
    );
  }

  Widget _buildDetailRow(String label, String value, {bool isTotal = false}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: const TextStyle(fontWeight: FontWeight.bold),
          ),
          Text(
            value,
            style: TextStyle(
              fontWeight: isTotal ? FontWeight.bold : FontWeight.normal,
              fontSize: isTotal ? 18 : 14,
              color: isTotal ? Colors.orange : null,
            ),
          ),
        ],
      ),
    );
  }

  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} '
           '${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
  }

  String _getPaymentMethodText(String method) {
    switch (method) {
      case 'cash':
        return 'نەق پۇل';
      case 'card':
        return 'كارتا';
      case 'wallet':
        return 'ئېلېكترونلۇق ھەميان';
      default:
        return method;
    }
  }

  String _getStatusText(String status) {
    switch (status) {
      case 'completed':
        return 'تاماملاندى';
      case 'pending':
        return 'كۈتۈۋاتىدۇ';
      case 'cancelled':
        return 'بىكار قىلىندى';
      default:
        return status;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                flex: 2,
                child: TextField(
                  controller: _searchController,
                  decoration: InputDecoration(
                    hintText: 'سودا خاتىرىسى ئىزدەش...',
                    prefixIcon: const Icon(Icons.search),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: DropdownButtonFormField<String>(
                  value: _selectedDateRange,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  items: const [
                    DropdownMenuItem(value: 'today', child: Text('بۈگۈن')),
                    DropdownMenuItem(value: 'week', child: Text('بۇ ھەپتە')),
                    DropdownMenuItem(value: 'month', child: Text('بۇ ئاي')),
                    DropdownMenuItem(value: 'year', child: Text('بۇ يىل')),
                  ],
                  onChanged: (value) {
                    if (value != null) {
                      setState(() {
                        _selectedDateRange = value;
                        _filterSales();
                      });
                    }
                  },
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: DropdownButtonFormField<String>(
                  value: _selectedStatus,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  items: const [
                    DropdownMenuItem(value: 'all', child: Text('بارلىق ھالەت')),
                    DropdownMenuItem(value: 'completed', child: Text('تاماملانغان')),
                    DropdownMenuItem(value: 'pending', child: Text('كۈتۈۋاتقان')),
                    DropdownMenuItem(value: 'cancelled', child: Text('بىكار قىلىنغان')),
                  ],
                  onChanged: (value) {
                    if (value != null) {
                      setState(() {
                        _selectedStatus = value;
                        _filterSales();
                      });
                    }
                  },
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          
          Expanded(
            child: Card(
              child: ListView.builder(
                itemCount: _filteredSales.length,
                itemBuilder: (context, index) {
                  final sale = _filteredSales[index];
                  return ListTile(
                    title: Text('${sale.customerName} - ${sale.id}'),
                    subtitle: Text(
                      '${_formatDate(sale.date)} - ${_getStatusText(sale.status)}',
                    ),
                    trailing: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          '¥${sale.totalAmount.toStringAsFixed(2)}',
                          style: const TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 16,
                          ),
                        ),
                        const SizedBox(width: 8),
                        IconButton(
                          icon: const Icon(Icons.visibility),
                          onPressed: () => _showSaleDetails(sale),
                          color: Colors.blue,
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
} 